<template>
    <div class="el-table el-table--fit el-table--striped el-table--enable-row-hover el-table--enable-row-transition">
        <!-- 操作行 -->
        <div>
            <el-button size="small" type="primary" @click="save" v-show="canEdit">保存报价</el-button>
            <el-button size="small" type="warning" @click="publish(2,'正式报价') " v-show="data && data.status < 3  ">发布正式报价</el-button>
            <el-button size="small" @click="publish(2,'口头报价')" v-show="data && data.status == 1 ">发布口头报价</el-button>
            <el-button size="small" type="info" @click="exportXls()">导出Excel</el-button>
        </div>
        <!-- 列表 -->
        <table size="mini" class="el-table el-table--fit el-table--striped el-table--enable-row-hover el-table--enable-row-transition product">
            <tr>
                <th style="text-align:center;width:65px;">序号</th>
                <th style="width:200px;">项目名称</th>
                <th>生产厂家</th>
                <th>型号规则</th>
                <th style="width:80px;">数量</th>
                <th style="width:80px;">单位</th>
                <th style="width:120px;">单价(元)</th>
                <th style="width:120px;">合价(元)</th>
                <th>备注</th>
            </tr>
            <template v-for="(type, index) in types">
                <!-- 产品分类 小标题行 -->
                <tr v-if="canEdit || (typeProducts[type.id] && typeProducts[type.id].length>0 )">
                    <td colspan="9">
                        {{ xh[index] }}、{{ type.name }}
                        <i v-if="canEdit" class="el-icon-plus" @click="add(type)"></i>
                    </td>
                </tr>
                <!-- 产品明细 内容行 -->
                <tr v-for="(product,xh) in typeProducts[type.id] || []">
                    <td style="text-align:center;">{{ xh+1 }}</td>
                    <td>
                        <el-select v-if="canEdit" v-model="product.product_id" placeholder="请选择" @change="selectProduct(product, type)">
                            <el-option v-for="item in baseProducts[type.id]" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                        <span v-else>
                            {{ product.product_name }}
                        </span>
                        <p v-if="canEdit" style="font-size:10px;color:blue;" @click="typeProducts[type.id].splice(xh,1)">删除</p>
                    </td>
                    <td> {{ product.product_factory }}</td>
                    <td> {{ product.product_type }}</td>
                    <td>
                        <el-input v-if="canEdit" @change="sum(product, type)" type="number" v-model="product.num"></el-input>
                        <span v-else> {{ product.num }}</span>
                    </td>
                    <td> {{ product.product_unit }}</td>
                    <td>
                        <el-input v-if="canEdit" @change="sum(product, type)" type="number" v-model="product.sale_price"></el-input>
                        <span v-else> {{ product.sale_price }}</span>
                    </td>
                    <td> {{ product.sale_amount | formatMoney(2) }}</td>
                    <td>
                        <el-input v-if="canEdit" type="text" v-model="product.remark"></el-input>
                        <span v-else> {{ product.remark }}</span>
                    </td>
                </tr>
                <tr v-show="typeProducts[type.id] && typeProducts[type.id].length > 0">
                    <td style="text-align:center;">合价</td>
                    <td colspan="6"></td>
                    <td>
                        {{ type.sum }}
                    </td>
                    <td>
                    </td>
                </tr>
            </template>
            <!-- 总计行 -->
            <tr>
                <td colspan="9">
                    {{ xh[types.length] }}、总价（{{ sumRow.text }}）
                </td>
            </tr>
            <tr>
                <td style="text-align:center;">1</td>
                <td>合价</td>
                <td colspan="5">
                    {{ sumRow.text }}
                </td>
                <td>
                    {{ sumRow.sum | formatMoney(2) }}
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td style="text-align:center;">2</td>
                <td>两年维护费</td>
                <td colspan="5">
                    （{{ sumRow.text }}） * 10%
                </td>
                <td>
                    {{ sumRow.fee | formatMoney(2) }}
                </td>
            </tr>
            <tr>
                <td style="text-align:center;">3</td>
                <td>总价</td>
                <td colspan="5">
                    合计金额大写：{{ sumRow.total | smalltoBIG }}
                </td>
                <td>
                    {{ sumRow.total | formatMoney(2) }}
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td style="text-align:center;">4</td>
                <td>最终合价</td>
                <td colspan="5">
                    合计金额大写：{{ sumRow.confirm | smalltoBIG }}
                </td>
                <td>
                    <el-input v-if="canEdit" type="number" v-model="sumRow.confirm" />
                    <span v-else> {{ sumRow.confirm | formatMoney(2) }}</span>
                </td>
                <td>
                </td>
            </tr>
        </table>
    </div>
</template>
<script>
    import { mapGetters, mapState } from 'vuex'
    import _ from 'lodash'
    import api from '@/api/product'
    import batchApi from '@/api/batch'

    export default {
        name: 'batch_edit',
        data() {
            return {
                xh: ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十',
                    '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八', '十九', '二十',
                    '二十一', '二十二', '二十三', '二十四', '二十五', '二十六', '二十七', '二十八', '二十九', '三十',
                    '三十一', '三十二', '三十三', '三十四', '三十五', '三十六', '三十七', '三十八', '三十九', '四十'
                ],
                types: [], //产品分类
                typeProducts: {}, //分类产品，存放获取的批次产品信息
                baseProducts: {}, //产品基础数据源
                sumRow: {//总计
                    sum: 0,//汇总金额
                    confirm: 0,//确认金额
                    fee: 0,
                    total: 0,
                    text: '',
                },
                //报价批次信息
                canEdit: true, //模式
            }
        },
        computed: {
            ...mapGetters([
                'dicArray', 'dicObj'
            ]),
            ...mapState({
                data: state => state.batch.data,
            }),

            customer_id() {
                return this.$route.query.customer_id
            }
        },
        async created() {
            //加载数据字典
            await this.$store.dispatch('loadDic')

            //获取所有产品 分类存放
            var ret = await api.index()
            this.baseProducts = _.groupBy(ret.data.rows, 'category')
            //读取批次信息
            this.batch_id = this.$route.query.oid
            await this.getList()

            //设置编辑模式
            this.canEdit = this.batch_id == null || this.data.status == 1

            //获取所有产品分类
            let arr = this.dicArray['产品分类']
            let all_types = _.sortBy(arr, item => item.value)

            //遍历分类 读取产品放入分类中
            for (let type of all_types) {
                //如果已经加载了数据，优先选择已经有的数据
                let products = this.typeProducts[type.id] || []
                type.sum = this.sum1(products, 'sale_amount')
                if (!this.canEdit && products.length == 0) {
                    continue;
                }
                this.$set(this.typeProducts, type.id, products)
                this.types.push(type)
            }

            //获取汇总公式 如果是可编辑模式，获取产品分类，如果不是，则获取分组后的数据长度

            var xhs = _.take(this.xh, this.canEdit ? this.types.length : Object.keys(this.typeProducts).length)
            this.sumRow.text = xhs.join('+')
        },
        methods: {
            sum1(items, field) { //汇总
                let val = 0
                for (let item of items) {
                    val += item[field] == null ? 0 : parseFloat(item[field])
                }
                return val
            },
            async getList() {
                await this.$store.dispatch('batch/getProduct', { id: this.batch_id, copy_id: this.$route.query.copy_id })
                if (!this.data) return
                this.sumRow.sum = this.data.sum
                this.sumRow.fee = this.data.fee
                this.sumRow.total = this.data.total
                this.sumRow.confirm = this.data.confirm
                if (this.data.batch_products)
                    this.typeProducts = _.groupBy(this.data.batch_products, 'product_category')
            },
            add(type) { //新增产品数据
                let { id } = type
                this.typeProducts[id] = this.typeProducts[id] || []
                this.typeProducts[id].push({
                    product_id: null,
                    product_name: null,
                    product_type: null,
                    product_price: null,
                    sale_price: null,
                    sale_amount: 0,
                    product__factory: null,
                    product__category: id,
                    remark: null,
                    num: 0,
                })
            },
            selectProduct(product, type) {
                //获取选中的产品
                var selected = _.find(this.baseProducts[type.id], (item) => item.id === product.product_id)
                if (selected) {
                    product.product_id = selected.id
                    product.product_name = selected.name
                    product.product_type = selected.type
                    product.sale_price = selected.guide_price
                    product.product_factory = selected.factory
                    product.product_unit = selected.unit
                    product.remark = ''
                    product.product_category = selected.category
                }
                this.sum(product, type)
            },
            sum(product, type) { //汇总
                //汇总当前产品
                product.sale_amount = product.num * product.sale_price

                let products = this.typeProducts[type.id]
                var val = 0
                for (let item of products) {
                    val += (item.num * item.sale_price) || 0
                }
                type.sum = val
                val = 0
                for (let item of this.types) {
                    val += item.sum
                }
                this.sumRow.sum = val
                this.sumRow.fee = val * 0.1
                this.sumRow.total = val * 1.1
                this.sumRow.confirm = Math.round(this.sumRow.total, 2)
            },
            async save() { //保存草稿报价
                let data = Object.assign({
                    customer_id: this.customer_id
                }, this.sumRow)
                //将分组后的产品数据，转换为产品数组
                let list = []
                for (var key in this.typeProducts) {
                    list = list.concat(this.typeProducts[key])
                }
                data.products = list
                let ret = await batchApi.save(data)
                if (ret.success) {
                    this.$notify({
                        title: '成功',
                        message: '保存成功！',
                        type: 'success',
                        duration: 2000,
                    })
                    this.$router.go(-1)
                }
            },
            async publish(status, status_text) { //发布报价
                if (!this.data || !this.data.id) {
                    return
                }
                await this.$store.dispatch('batch/publish', {
                    status,
                    status_text,
                    id: this.data.id
                })
                this.canEdit = false
            },
            async exportXls() {
                let columns = [
                    [
                        { header: '序号', key: 'xh', width: 5 },
                        { header: '项目名称', key: 'index', width: 15 },
                        { header: '生产厂家', key: 'remain', width: 15 },
                        { header: '型号规则', key: 'curr', width: 15 },
                        { header: '数量', key: 'curr', width: 15 },
                        { header: '单位', key: 'curr', width: 15 },
                        { header: '单价(元)', key: 'curr', width: 15 },
                        { header: '合价(元)', key: 'curr', width: 15 },
                        { header: '备注', key: 'curr', width: 15 },
                    ]
                ]

                let data = []

                // 增加数据行
                let xh = 0
                for (let t of this.types) {
                    let xh_text = this.xh[xh]
                    columns.push([{ header: xh_text + '、' + t.name, colspan: 9 }])
                    let p_xh = 1
                    for (var p of this.typeProducts[t.id]) {
                        let col = []
                        col.push({ header: p_xh++ })
                        col.push({ header: p.product_name })
                        col.push({ header: p.product_factory })
                        col.push({ header: p.product_type })
                        col.push({ header: p.product })
                        col.push({ header: p.product_unit })
                        col.push({ header: p.sale_price })
                        col.push({ header: p.sale_amount })
                        col.push({ header: p.remark })
                        // 增加产品行
                        columns.push(col)
                    }
                    xh++
                }

                // 增加汇总行
                columns.push([{ header: this.xh[xh++] + '、总价', colspan: 9 }])
                columns.push([
                    { header: 1 },
                    { header: '合价' },
                    { header: this.sumRow.text, colspan: 5 },
                    { header: this.sumRow.sum },
                ])
                columns.push([
                    { header: 2 },
                    { header: '两年维护费' },
                    { header: '（ ' + this.sumRow.text + '） * 10%', colspan: 5 },
                    { header: this.sumRow.fee },
                ])
                columns.push([
                    { header: 3 },
                    { header: '总价' },
                    { header: this.smalltoBIG(this.sumRow.total), colspan: 5 },
                    { header: this.sumRow.total },
                ])
                columns.push([
                    { header: 4 },
                    { header: '总价' },
                    { header: this.smalltoBIG(this.sumRow.confirm), colspan: 5 },
                    { header: this.sumRow.confirm },
                ])

                this.download('/api/file/xls', {
                    filename: `报价表`,
                    columns: JSON.stringify(columns),
                    data: JSON.stringify(data)
                })


            },
            download(actionUrl, parms) {
                var form = document.createElement("form")
                form.style.display = "none"
                form.action = actionUrl
                form.method = "post"
                document.body.appendChild(form)

                for (var key in parms) {
                    var input = document.createElement("input")
                    input.type = "hidden"
                    input.name = key
                    input.value = parms[key]
                    //input.value = encodeURIComponent(parms[key]);
                    form.appendChild(input)
                }
                form.submit()
            }
        }
    }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
    .product {
        border-collapse: collapse;
        width: 98%;
        margin: auto;

        tr {
            height: 40px;
        }

        th {
            background-color: #fff;
            border: 1px solid #dfe6ec;
            text-align: center;
        }

        td {
            border: 1px solid #dddddd;

        }
    }

</style>
